package com.ncbee.base.web.base;

import com.ncbee.base.model.enums.ResultCode;
import com.ncbee.base.model.vo.Result;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author: fengzirong
 * @Description:全局异常处理
 * @Date:Create in 21:49 2018/11/24
 */
@ControllerAdvice
public class BaseExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);

    /**
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Result handleIllegalParamException(BindException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        if (errors.size() > 0){
           String [] errorCodes=errors.get(0).getCodes();
           logger.info(errorCodes[0]);
        }
        Result result = Result.getInstance(ResultCode.BASE_ERROR);
        result.setMsg("参数不合法");
        return result;
    }

    @ResponseBody
    @ExceptionHandler(UnknownAccountException.class)
    public Result UnknownAccountException(UnknownAccountException e) {
        String msg= e.getMessage();
        Result result = Result.getInstance(ResultCode.BASE_ERROR);
        result.setMsg(msg);
        return result;
    }
    @ResponseBody
    @ExceptionHandler(LockedAccountException.class)
    public Result LockedAccountException(LockedAccountException e) {
        String msg= e.getMessage();
        Result result = Result.getInstance(ResultCode.BASE_ERROR);
        result.setMsg(msg);
        return result;
    }

    /**
     * 无权限异常
     * @param e
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public String AuthorizationException(AuthorizationException e) {
        return "error/unAccess";
    }
}
